import json
import requests
import os
import time


def get_token(ID, SECRET):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}"
    res = requests.get(url).json()
    return res['access_token']


def get_token_main(ID, SECRET):
    """
    param ID:企业标识
    param SECRET:应用Secret
    return:token
    """
    if os.path.exists('access_token.json'):
        with open('access_token.json', 'r+', encoding='utf8') as fp:
            token_data = json.loads(fp.read())
            if token_data['old_time'] + token_data['expires_in'] < time.time():
                print('已过期')
                url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}"
                res = requests.get(url).json()
                dic = {'old_time': time.time(), 'expires_in': res['expires_in'], 'access_token': res['access_token']}
                config = json.dumps(dic, indent=4)
                fp.write(config)
            else:
                return token_data['access_token']
    else:
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}"
        res = requests.get(url).json()
        if res['errcode'] == 0:
            with open('access_token.json', 'w', encoding='utf8') as fp:
                dic = {'old_time': time.time(), 'expires_in': res['expires_in'], 'access_token': res['access_token']}
                config = json.dumps(dic, indent=4)
                fp.write(config)
                return res['access_token']


def wx(content,ID,SECRET):
    """
    param content:消息内容
    param ID:企业标识
    param SECRET:应用Secret
    return:token
    """
    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={get_token(ID,SECRET)}"
    data = {
        "touser": "zhangluo",
        "msgtype": "text",
        "agentid": 1000002,
        "text": {
            "content": content
        },
        "safe": 0,
        "enable_id_trans": 0,
        "enable_duplicate_check": 0
    }
    resp = requests.post(url=url, data=json.dumps(data))
    errcode=resp.json()["errcode"]
    if errcode==0:
        return 0
    else:
        return resp
